package rensoft.jre.io;

import org.apache.commons.io.FileUtils;

import java.io.FileFilter;
import java.io.IOException;
import java.util.Iterator;

import static cs.java.lang.Lang.exception;
import static cs.java.lang.Lang.list;
import static cs.java.lang.Lang.asStringArray;

import cs.java.collections.List;







public class DirImpl extends PathImpl implements Dir {

  public DirImpl(Dir parent, String... path) {
    setPath(parent.getFullPath(), path);
  }

  public DirImpl(java.io.File file) {
    jreFile = file;
    check();
  }

  public DirImpl(String parent, Dir... path) {
    if (path.length == 0)
      setPath(parent);
    else setPath(parent, asStringArray((Object[]) path));
  }

  @Override
  public void copyTo(Dir destination) {
    try {
      destination.create();
      FileUtils.copyDirectory(jreFile, destination.toJRE(), true);
    } catch (IOException ex) {
      throw exception(ex);
    }
  }

  public void copyTo(Dir destination, FileFilter filter) {
    try {
      destination.create();
      FileUtils.copyDirectory(jreFile, destination.toJRE(), filter);
    } catch (IOException ex) {
      throw exception(ex);
    }
  }

  public void create() {
    if (jreFile.exists()) return;
    jreFile.mkdirs();
    if (!jreFile.exists()) throw exception("Not created", this);
  }

  public void delete() {
    try {
      org.apache.commons.io.FileUtils.deleteDirectory(jreFile);
    } catch (IOException ex) {
      throw exception(ex);
    }
  }

  public List<Path> getChilds() {
    List<Path> childs = list();
    for (String path : jreFile.list())
      childs.add(PathImpl.create(getPath() + SEPARATOR + path));
    return childs;
  }

  public boolean isDir() {
    return true;
  }

  public Iterator<Path> iterator() {
    mustExist();
    List<Path> list = list();
    for (String path : jreFile.list())
      list.add(PathImpl.create(getPath() + SEPARATOR + path));
    return list.iterator();
  }

  @Override
  protected void check() {
    if (jreFile.isFile()) throw exception("Not dir");
  }

  private void mustExist() {
    if (!exists()) throw exception("Dir not existing", getFullPath());
  }

}
